<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick } from "vue";
import { invoke } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
import { getCurrentWindow, LogicalPosition } from "@tauri-apps/api/window";
import { ElMessage } from 'element-plus';
import SearchBar from './components/SearchBar.vue';
import ShortcutGrid from './components/ShortcutGrid.vue';
import type { Shortcut } from './types';

const shortcuts = ref<Shortcut[]>([]);
const searchQuery = ref('');
const searchBarRef = ref();
const shortcutGridRef = ref();

// 拖拽相关状态
const isDragging = ref(false);
const lastMousePos = ref({ x: 0, y: 0 });
const dragStartPos = ref({ x: 0, y: 0 });
const windowStartPos = ref({ x: 0, y: 0 });

// 监听搜索查询变化，重置选中索引
watch(searchQuery, () => {
  shortcutGridRef.value?.resetSelectedIndex();
});

// 获取桌面快捷方式
async function getDesktopShortcuts() {
  try {
    const result = await invoke<Shortcut[]>("get_desktop_shortcuts");
    shortcuts.value = result;
  } catch (error) {
    console.error('获取桌面快捷方式失败:', error);
    ElMessage.error('获取快捷方式失败: ' + error);
  }
}

// 启动快捷方式
async function launchShortcut(shortcut: Shortcut) {
  try {
    await invoke("launch_shortcut", { shortcutPath: shortcut.path });
    // 移除成功消息提示
  } catch (error) {
    console.error('启动快捷方式失败:', error);
    ElMessage.error('启动失败: ' + error);
  }
}

// 刷新快捷方式列表
function refreshShortcuts() {
  console.log('开始刷新快捷方式列表...');
  ElMessage.success('正在刷新快捷方式...');
  getDesktopShortcuts();
}

// 隐藏到托盘
async function hideToTray() {
  try {
    await invoke('hide_window');
  } catch (error) {
    console.error('隐藏窗口失败:', error);
    ElMessage.error('隐藏窗口失败');
  }
}

// 处理搜索框失焦
function handleBlurSearch() {
  searchBarRef.value?.blur();
}

/**
 * 处理窗口获得焦点事件
 * 当窗口从后台切换到前台时自动聚焦搜索框并清空内容
 */
function handleWindowFocus() {
  // 延迟聚焦，确保窗口完全激活
  setTimeout(() => {
    // 清空搜索框内容
    searchQuery.value = '';
    // 聚焦搜索框
    searchBarRef.value?.focus();
    console.log('[DEBUG] 窗口获得焦点，清空并聚焦搜索框');
  }, 100);
}

/**
 * 处理鼠标按下事件，开始拖拽
 * @param event 鼠标事件
 */
async function handleMouseDown(event: MouseEvent) {
  try {
    isDragging.value = true;
    // 使用screenX/screenY获取更准确的屏幕坐标
    dragStartPos.value = { x: event.screenX, y: event.screenY };
    lastMousePos.value = { x: event.screenX, y: event.screenY };
    
    // 记录窗口初始位置
    const appWindow = getCurrentWindow(); 
    const currentPos = await appWindow.outerPosition();
    windowStartPos.value = { x: currentPos.x, y: currentPos.y };
    
    console.log('[DEBUG] 开始拖拽 - 鼠标屏幕位置:', dragStartPos.value, '窗口位置:', windowStartPos.value);
  } catch (error) {
    console.error('[ERROR] 初始化拖拽失败:', error);
    isDragging.value = false;
  }
}

/**
 * 处理鼠标移动事件，执行拖拽
 * @param event 鼠标事件
 */
async function handleMouseMove(event: MouseEvent) {
  if (!isDragging.value) return;
  
  // 使用screenX/screenY获取更准确的屏幕坐标
  const currentScreenX = event.screenX;
  const currentScreenY = event.screenY;
  
  // 计算相对于拖拽开始位置的偏移量
  const totalDeltaX = currentScreenX - dragStartPos.value.x;
  const totalDeltaY = currentScreenY - dragStartPos.value.y;
  
  // 计算新的窗口位置（基于初始窗口位置）
  const newX = windowStartPos.value.x + totalDeltaX;
  const newY = windowStartPos.value.y + totalDeltaY;
  
  console.log('[DEBUG] 拖拽移动 - 屏幕坐标:', currentScreenX, currentScreenY, '总偏移:', totalDeltaX, totalDeltaY, '新窗口位置:', newX, newY);
  
  // 防抖：只有当移动距离足够大时才更新窗口位置
  const deltaFromLast = Math.abs(currentScreenX - lastMousePos.value.x) + Math.abs(currentScreenY - lastMousePos.value.y);
  if (deltaFromLast < 3) return;
  
  try {
    const appWindow = getCurrentWindow();
    await appWindow.setPosition(new LogicalPosition(newX, newY));
    
    // 更新上次鼠标位置用于防抖
    lastMousePos.value = { x: currentScreenX, y: currentScreenY };
    
    console.log('[DEBUG] 窗口移动成功');
  } catch (error) {
    console.error('[ERROR] 移动窗口失败:', error);
  }
}

/**
 * 处理鼠标释放事件，结束拖拽
 */
function handleMouseUp() {
  if (isDragging.value) {
    isDragging.value = false;
    console.log('[DEBUG] 结束拖拽');
  }
}

// 存储事件监听器的引用，用于清理
let refreshUnlisten: (() => void) | null = null;

// 组件挂载时获取快捷方式
onMounted(async () => {
  try {
    await getDesktopShortcuts();
  } catch (error) {
    console.error('初始化失败:', error);
    ElMessage.error('应用初始化失败: ' + error);
  }
  
  // 自动聚焦搜索框 - 确保DOM完全渲染和窗口显示后再聚焦
  await nextTick();
  setTimeout(() => {
    searchBarRef.value?.focus();
    console.log('[DEBUG] 自动聚焦搜索框');
  }, 300);
  
  // 添加窗口焦点事件监听器
  window.addEventListener('focus', handleWindowFocus);
  console.log('[DEBUG] 已添加窗口焦点事件监听器');
  
  // 添加全局鼠标事件监听器用于拖拽
  document.addEventListener('mousemove', handleMouseMove);
  document.addEventListener('mouseup', handleMouseUp);
  console.log('[DEBUG] 已添加拖拽事件监听器');
  
  // 监听来自后端的刷新事件
  try {
    refreshUnlisten = await listen('refresh-shortcuts', () => {
      console.log('[DEBUG] 收到刷新快捷方式事件');
      refreshShortcuts();
    });
    console.log('[DEBUG] 已添加刷新事件监听器');
  } catch (error) {
    console.error('添加刷新事件监听器失败:', error);
  }
});

// 组件卸载时清理事件监听器
onUnmounted(() => {
  window.removeEventListener('focus', handleWindowFocus);
  console.log('[DEBUG] 已移除窗口焦点事件监听器');
  
  // 清理拖拽事件监听器
  document.removeEventListener('mousemove', handleMouseMove);
  document.removeEventListener('mouseup', handleMouseUp);
  console.log('[DEBUG] 已移除拖拽事件监听器');
  
  // 清理刷新事件监听器
  if (refreshUnlisten) {
    refreshUnlisten();
    console.log('[DEBUG] 已移除刷新事件监听器');
  }
});
</script>

<template>
  <div class="app-container">
    <div class="search-section" @mousedown="handleMouseDown">
      <SearchBar
        ref="searchBarRef"
        v-model="searchQuery"
        @hide-to-tray="hideToTray"
      />
    </div>
    
    <div class="content-section">
      <ShortcutGrid
        ref="shortcutGridRef"
        :shortcuts="shortcuts"
        :search-query="searchQuery"
        @launch-shortcut="launchShortcut"
        @refresh-shortcuts="refreshShortcuts"
        @hide-to-tray="hideToTray"
        @blur-search="handleBlurSearch"
      />
    </div>
  </div>
</template>
  
<style lang="scss" scoped>
.app-container {
  height: 100vh;
  background: transparent;
  border-radius: 16px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  position: relative;
  
  /* 第一层：背景图层 */
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image: url('@/assets/bg.jpg');
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    opacity: 0.4;
    z-index: -3;
    border-radius: 16px;
    filter: blur(3px);
  }
  
  /* 第二层：彩色渐变层 */
  &::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: -2;
    background: 
      /* 第一个不规则图形 - 蓝紫色 */
      radial-gradient(ellipse 40% 60% at 20% 30%, rgba(147, 51, 234, 0.4) 0%, transparent 50%),
      /* 第二个不规则图形 - 粉红色 */
      radial-gradient(ellipse 50% 40% at 80% 20%, rgba(236, 72, 153, 0.35) 0%, transparent 50%),
      /* 第三个不规则图形 - 青色 */
      radial-gradient(ellipse 60% 50% at 60% 80%, rgba(14, 165, 233, 0.3) 0%, transparent 50%),
      /* 第四个不规则图形 - 橙色 */
      radial-gradient(ellipse 45% 55% at 10% 70%, rgba(249, 115, 22, 0.35) 0%, transparent 50%),
      /* 第五个不规则图形 - 绿色 */
      radial-gradient(ellipse 35% 45% at 90% 60%, rgba(34, 197, 94, 0.3) 0%, transparent 50%);
    border-radius: 16px;
  }
}

/* 第三层：毛玻璃效果层 */
.app-container {
  backdrop-filter: blur(20px) saturate(1.2);
  -webkit-backdrop-filter: blur(20px) saturate(1.2);
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 
    inset 0 1px 0 rgba(255, 255, 255, 0.3),
    0 8px 32px rgba(0, 0, 0, 0.15);
}

/* 确保内容在背景层之上 */
.app-container > * {
  position: relative;
  z-index: 3;
}



.search-section {
  flex-shrink: 0;
  padding: 0;
}

.content-section {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 12px;
}


/* 自定义滚动条样式 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

/* 隐藏滚动条的上下箭头按钮 */
::-webkit-scrollbar-button {
  display: none;
}

::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 4px;
  transition: background 0.2s ease;
}

::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.5);
}

::-webkit-scrollbar-thumb:active {
  background: rgba(255, 255, 255, 0.6);
}

::-webkit-scrollbar-corner {
  background: rgba(255, 255, 255, 0.1);
}

/* Firefox 滚动条样式 */
* {
  scrollbar-width: thin;
  scrollbar-color: rgba(255, 255, 255, 0.3) rgba(255, 255, 255, 0.1);
}

</style>

<style>
/* 全局样式重置 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  background: transparent;
}

#app {
  height: 100vh;
}
</style>